<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\data\material;

use app\enum\AnalysisEnum;
use app\model\mongo\MongoMaterialPicDayStatModel;
use app\model\mongo\MongoMaterialVideoDayStatModel;
use app\model\mongo\MongoStatModel;
use app\service\analysis\data\material\pic\PicMonthStatService;
use app\service\analysis\data\material\video\VideoMonthStatService;
use app\service\BaseService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

final class MaterialMonthStatService extends BaseService
{
    /**
     * @var int 任务类型
     */
    protected int $taskType = 0;

    public function __construct(int $taskType = 0)
    {
        $this->taskType = $taskType;
    }

    /**
     * 获取已变数据.
     *
     * @return array|Collection|MongoMaterialPicDayStatModel[]|MongoMaterialVideoDayStatModel[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList()
    {
        if ($this->taskType == AnalysisEnum::TASK_TYPE_VIDEO) {
            return (new MongoMaterialVideoDayStatModel())->where('is_change', '=', MongoStatModel::IS_CHANGE_YES)->field(true)->page(1)->limit(20)->select();
        }
        if ($this->taskType == AnalysisEnum::TASK_TYPE_PICTURE) {
            return (new MongoMaterialPicDayStatModel())->where('is_change', '=', MongoStatModel::IS_CHANGE_YES)->field(true)->page(1)->limit(20)->select();
        }
        return [];
    }

    /**
     * 执行脚本.
     * @param MongoStatModel $model 汇总模型
     */
    public function runTask(MongoStatModel $model): bool
    {
        if (! $model->getKey()) {
            return self::setError('未知素材日汇总模型');
        }

        if ($this->taskType == AnalysisEnum::TASK_TYPE_VIDEO) {
            return (new VideoMonthStatService($model, $this->taskType))->setStat();
        }
        if ($this->taskType == AnalysisEnum::TASK_TYPE_PICTURE) {
            return (new PicMonthStatService($model, $this->taskType))->setStat();
        }
        return self::setError('未知素材类型');
    }
}
